<!--
 * @file 轨迹监控页面
 * @description 实时监控和历史轨迹查询、回放功能页面(简化版)
 * @date 2024-06-25
 * @update 更新：修改为点击设备即查询轨迹，不再自动查询
 -->
<template>
  <view class="monitor-page">
    <app-header />
    <!-- 主界面 -->
    <view class="monitor-page__main">
      <!-- 轨迹播放器 - 已移除 -->
      
      <!-- GPS管理面板 -->
      <GPSManagePanel
        v-if="!isMobileView"
        :expanded="showDevicePanel"
        :selected-device-id="selectedDeviceId"
        :initialTab="activeTab"
        class="monitor-page__device-panel"
        @update:expanded="showDevicePanel = $event"
        @update:selected-device-id="selectedDeviceId = $event"
        @tab-change="handleTabChange"
        @date-change="handleDateChange"
        @device-select="handleDeviceSelect"
        @search="handleSearch"
        @status-filter="handleStatusFilter"
      />
      
      <!-- 主地图容器 -->
      <view class="monitor-page__map-container">
        <!-- 移动端视图下的设备选择 -->
        <DeviceSelector
          v-if="isMobileView"
          :device-options="deviceOptions"
          :selected-device-id="selectedDeviceId"
          @change="handleDeviceChange"
        />
        
        <!-- 根据模式显示轨迹查看器或常规地图 -->
        <track-viewer
          v-if="shouldShowTrackViewer"
          ref="trackViewerRef"
          :device-id="selectedDeviceId"
          :start-time="startTime"
          :end-time="endTime"
          :auto-play="false"
          class="monitor-page__track-viewer"
          @track-loaded="handleTrackLoaded"
          @track-error="handleTrackError"
        />
        
        <div v-else class="monitor-page__map">
          <div v-if="!mapLoaded" class="monitor-page__map-loading">
            <div class="monitor-page__map-loading-spinner"></div>
            <span class="monitor-page__map-loading-text">正在加载地图...</span>
          </div>
          
          <map-container 
            ref="mapRef"
            :center="mapCenter"
            :zoom="mapZoom"
            @ready="handleMapReady"
            @click="handleMapClick"
          />
        </div>
      </view>
    </view>
  </view>
</template>

<script setup lang="ts">
// @ts-ignore
import { ref, computed, onMounted, watch, onUnmounted, defineAsyncComponent } from 'vue';
import { useDeviceStore } from '@/stores/modules/device';
import { throttle } from '@/utils/helpers/common';
// 引入新的轨迹管理hook
import { useTrackViewer } from '@/hooks/monitor/useTrackViewer';

// 基础组件立即导入
import AppHeader from '@/components/layout/AppHeader.vue';

// 懒加载非关键组件
const MapContainer = defineAsyncComponent(() => import('@/components/monitor/map/MapContainer.vue'));
// 移除 TrackPlayer 组件的引用
const TrackViewer = defineAsyncComponent(() => import('@/components/monitor/TrackViewer.vue'));
const GPSManagePanel = defineAsyncComponent(() => import('@/components/monitor/gpsPanels/GPSManagePanel.vue'));

// 地图相关状态
const mapState = {
  ref: ref(null),
  loaded: ref(false),
  center: ref({ lng: 116.404, lat: 39.915 }),
  zoom: ref(15)
};

// 视图和面板状态
const uiState = {
  isMobileView: ref(window.innerWidth < 768),
  showDevicePanel: ref(true)
};

// 设备和标签状态
const deviceState = {
  selectedDeviceId: ref(''),
  activeTab: ref<'realtime' | 'history'>('realtime'),
  deviceOptions: ref<string[]>([])
};

// 使用轨迹管理hook
const trackViewerRef = ref(null);
const {
  startTime,
  endTime,
  shouldLoadTrack,
  resetTrackData,
  prepareTrackQuery,
  handleTrackLoaded: onTrackLoaded,
  handleTrackError} = useTrackViewer();

// 解构状态以便于模板中使用
const { ref: mapRef, loaded: mapLoaded, center: mapCenter, zoom: mapZoom } = mapState;
const { isMobileView, showDevicePanel } = uiState;
const { selectedDeviceId, activeTab, deviceOptions } = deviceState;

// 获取设备store
const deviceStore = useDeviceStore();

// 移除已删除的组件相关的计算属性
// const showTrackPlayer = computed(() => trackPoints.value.length > 0);

// 计算属性：轨迹查看器显示条件
// Renamed to avoid conflict with property from useTrackManagement
const shouldShowTrackViewer = computed(() => 
  activeTab.value === 'history' && 
  !!selectedDeviceId.value && 
  !!startTime.value && 
  !!endTime.value && 
  shouldLoadTrack.value
);

/**
 * 处理地图准备好事件
 */
function handleMapReady() {
  mapLoaded.value = true;
  updateDeviceOptions();
}

/**
 * 更新设备选项列表
 */
function updateDeviceOptions() {
  deviceOptions.value = deviceStore.deviceList.map((device: { deviceId: any; }) => device.deviceId);
}

/**
 * 处理地图点击事件
 */
function handleMapClick(event: any) {
  console.log('地图点击', event);
}

/**
 * 处理标签切换
 */
function handleTabChange(tab: 'realtime' | 'history'): void {
  activeTab.value = tab;
  
  if (tab === 'history') {
    prepareTrackQuery(selectedDeviceId.value);
  } else {
    resetTrackData();
  }
}

/**
 * 处理时间范围变更
 */
function handleDateChange(date: string): void {
  // 从单一日期字符串创建开始和结束时间
  startTime.value = `${date}T00:00:00`;
  endTime.value = `${date}T23:59:59`;
  
  // 时间变更后如果已有选择设备，则重新查询轨迹
  if (selectedDeviceId.value && activeTab.value === 'history') {
    resetTrackData();
    shouldLoadTrack.value = true;
  }
}

/**
 * 统一处理设备选择
 */
function handleDeviceSelect(device: any) {
  // 更新选中的设备ID
  const deviceId = device?.deviceId || '';
  selectedDeviceId.value = deviceId;
  
  // 如果是取消选中设备（设备ID为空）
  if (!deviceId) {
    resetTrackData();
    return;
  }
  
  // 根据当前标签决定后续操作
  if (activeTab.value === 'history') {
    resetTrackData();
    
    // 如果有设备ID和时间范围，则触发轨迹加载
    if (startTime.value && endTime.value) {
      shouldLoadTrack.value = true;
    }
  } else if (activeTab.value === 'realtime') {
    mapZoom.value = 16; // 更新缩放级别
  }
}

/**
 * 处理设备变更（移动端视图）
 */
function handleDeviceChange(deviceId: string) {
  const device = deviceStore.deviceList.find((d: { deviceId: string; }) => d.deviceId === deviceId) || { deviceId };
  handleDeviceSelect(device);
}

/**
 * 处理设备搜索
 */
function handleSearch(keyword: string) {
  deviceStore.searchDevices(keyword);
}

/**
 * 处理状态过滤
 */
function handleStatusFilter(status: number) {
  deviceStore.filterByStatus(status);
}

/**
 * 处理轨迹加载完成
 */
function handleTrackLoaded(data: any) {
  onTrackLoaded(data);
}

// 监听设备列表变化
watch(() => deviceStore.deviceList, updateDeviceOptions, { immediate: true });

// 检测窗口大小变化
onMounted(() => {
  const handleResize = throttle(() => {
    isMobileView.value = window.innerWidth < 768;
  }, 200);
  
  window.addEventListener('resize', handleResize);
  
  onUnmounted(() => {
    window.removeEventListener('resize', handleResize);
  });
});
</script>

<style lang="scss" scoped>
.monitor-page {
  width: 100%;
  height: 100vh;
  display: flex;
  flex-direction: column;
  background-color: #f0f2f5;
  
  &__main {
    flex: 1;
    display: flex;
    overflow: hidden;
    position: relative;
  }
  
  &__map-container {
    flex: 1;
    position: relative;
    display: flex;
    flex-direction: column;
    overflow: hidden;
    width: 100%;
  }
  
  &__map {
    flex: 1;
    position: relative;
    width: 100%;
    height: 100%;
    
    &-loading {
      position: absolute;
      top: 0;
      left: 0;
      width: 100%;
      height: 100%;
      background-color: rgba(255, 255, 255, 0.85);
      display: flex;
      flex-direction: column;
      align-items: center;
      justify-content: center;
      z-index: 10;
      
      &-spinner {
        width: 50px;
        height: 50px;
        border-radius: 50%;
        border: 4px solid rgba(0, 0, 0, 0.1);
        border-top-color: #409EFF;
        animation: spin 1s linear infinite;
        margin-bottom: 20px;
      }
      
      &-text {
        font-size: 16px;
        color: #606266;
      }
    }
  }
  
  &__track-viewer {
    flex: 1;
    position: relative;
    width: 100%;
    height: 100%;
  }
  
  /* 移除轨迹播放器相关样式 */
}

@keyframes spin {
  to {
    transform: rotate(360deg);
  }
}

@media (max-width: 767px) {
  .monitor-page {
    &__device-panel {
      display: none;
    }
  }
}
</style> 